# -*- coding: utf-8 -*
import human
import blockengine
import village
import helper
import pygame
from tupleVector import *
import lib.selector, os

class cWoodChopper (human.cHuman, lib.selector.SelectItem):
    def __init__(self, grid, tPosPi=(0,0), img=None, depth=0, zBuffer=None):
        human.cHuman.__init__(self, "johnny", tPosPi, img, depth, zBuffer)
        lib.selector.SelectItem.__init__(self)
        self.grid = grid
        
        self.registerState ("harvest", self.callbackHarvest, ["walk", "harvest"])
        self.registerState ("idle", self.callbackIdle, ["idle"])
        self.registerState ("walk", self.callbackWalk, ["walk"])
        self.registerState ("gohome", self.callbackGoHome, ["walk"])
        self.registerState ("fleehome", self.callbackFleeHome, ["run"])
        
        self.harvestTimer = 0
        self.harvestTimerDelta = 1000   # ms = 1 second
        self.harvestedFood = 0
        self.harvestedFoodMax = 10
        
        self.consumeFoodTimer = 0
        self.consumeFoodTimerDelta = 2000 + helper.rndint (1000) 
        self.consumeFoodValue = 1 
        
        # load image for marking and selecting
        # TODO: use resource Manager
        self.setMarker(pygame.image.load (os.path.join("res","gfx","gui","marker.png")).convert())
        
    def callbackIdle (self, tArgs):
        pass
    def callbackWalk (self, tArgs):
        if tArgs[0]:
            self.setNewPathToTarget(self.grid, tArgs[0])
    def callbackHarvest (self, tArgs):
        " initialize state: go to random spot on field "
        if tArgs[0]: 
            village = tArgs[0]
            field = self.getHome().getField()
            # get all tiles tagged with field
            tags = self.grid.getObjsForTag (field)
            #print tags
            lTiles = [t for t in tags if isinstance (t, blockengine.cTile)]
            #print lTiles
            # select random tile on field
            if lTiles != []:
                r = helper.rndint (len(lTiles))
                #print r, lTiles, len(lTiles)
                # move there
                self.setNewPathToTarget(self.grid, lTiles[r], True)
                self.state.setActiveSet ("walk")
    def callbackGoHome (self, tArgs):
        tHomePi = self.getHome().tPosPi
        # Fake a position to go to
        #TODO: better solution, this is adapted to one image
        pos = vAdd (tHomePi,(75,85))
        t = self.grid.getTileAtPi(pos)
        print tHomePi, pos, t
        print self.grid.getObjsForTag(t)
        #print pos, tHomePi
        self.setNewPathToTarget(self.grid, t, ["blockinside"])
        #self.setNewPathToTarget(self.grid, self.getHome())
    def callbackFleeHome (self, tArgs):
        self.setNewPathToTarget(self.grid, self.getHome())
        self.speed = 2
            
    def getHomeVillage (self):
        obj = self.grid.getObjsForTag (self)
        l = [o for o in obj if isinstance(o, village.cVillage)]
        if l != []:
            return l[0]
        return None
    def getHome (self):
        obj = self.grid.getObjsForTag (self)
        l = [o for o in obj if isinstance(o, village.cHome)]
        if l != []:
            return l[0]
        return None
    def harvest (self):
        t = pygame.time.get_ticks()
        if self.harvestTimer + self.harvestTimerDelta < t:
            self.harvestTimer = t
            self.harvestedFood += 1
            if self.harvestedFood == self.harvestedFoodMax:
                v = self.getHomeVillage()
                self.callbackHarvest ([v])
                v.addFood (self.harvestedFood)
                self.harvestedFood = 0
    def consumeFood (self):
        " consume food, if something is there"
        t = pygame.time.get_ticks()
        if self.consumeFoodTimer + self.consumeFoodTimerDelta < t:
            self.consumeFoodTimer = t
            v = self.getHomeVillage()
            eaten = v.subFood (self.consumeFoodValue)
    
    # overwriten method for marking reasons
    def draw (self, screen, grid):
        # see cHuman.draw !!
        s = self.getDrawSurface()
        img = self.drawMarker(s)
        # tPosPi = topleft of image
        # so move image up and right to better fit on location
        # FIXME: this has to be a parameter somehow ...!! is that the proper way to deal with it?
        r = s.get_rect()
        pos = vSub (self.tPosPi, (r.w / 2, r.h / 2))
        screen.blit (img, grid.g2s(pos))
             
class cSkeleton (human.cHuman):
    def __init__(self, grid, tPosPi=(0,0), img=None, depth=0, zBuffer=None):
        human.cHuman.__init__(self, "skeleton", tPosPi, img, depth, zBuffer)
        self.grid = grid
        self.registerState ("attack", self.callbackAttack, ["attack"])
        self.registerState ("walk", self.callbackWalk, ["walk"])
        self.enemy = None
        self.enemyPosTile = None
    def callbackWalk (self, tArgs):  
        if tArgs!=():
            self.setNewPathToTarget(self.grid, tArgs[0])
            self.setSpeed (0.5)
    def attack (self, enemy):
        # is enemy the same as in last call, then check ist position
        # if it changed, then follow, otherwise stay on track
        # if enemy changed, calculate new track
        if self.enemy == enemy:
            enPos = self.grid.getTileAtPi (enemy.tPosPi)
            if self.enemyPosTile != enPos:
                self.enemyPosTile = enPos
                self.setNewPathToTarget(self.grid, enPos) 
        else:
            self.enemy = enemy
            enPos = self.grid.getTileAtPi (enemy.tPosPi)
            self.enemyPosTile = enPos
            #neig = self.grid.getNeighbourTiles (enPos)
            
            self.setNewPathToTarget(self.grid, enPos)
    def callbackAttack (self, tArgs):
        #if tArgs[0]:
        #    self.setNewPathToTarget(self.grid, tArgs[0])
        #    self.setSpeed(0.7)
            
        # finde ein tile das um das zieltile liegt und 
        # nicht von jemandem anderen besetzt ist
        
        self.attack (tArgs[0])
        return
    
        target = self.grid.getTileAtPi (obj.tPosPi)
        self.setNewPathToTarget(self.grid, target)
        return
        
        target = self.grid.getTileAtPi (obj.tPosPi)
        neig = self.grid.getNeighbourTiles (target) 
        found = None
        for n in neig:
            tags = self.grid.getObjsForTag (n)
            l = [t for t in tags if isinstance (t, blockengine.cSprite)]
            # delete myself from that list
            if self in l:
                l.remove(self)
            # empty lists contain no sprite so we can go there
            if l == []:
                found = n
                break
        if found != None:
            self.setNewPathToTarget(self.grid, found)
            self.setSpeed (0.7)
        
#        for n in neig:
#            tags = grid.getObjsForTag (n)
#            for t in tags:
#                if isinstance (t, cSprite):
#                    if not self.grid.hasTag (t, "blocking"):
#                        self.setNewPathToTarget(self.grid, n)
#                        self.setSpeed (0.7)
#                        found = True
#                        break
#            if found == True:
#                break
            
            